#include "httphelper.h"
using namespace FsxWsUtils;

//
// Parameter to boolean ("flag")
//
const bool HttpHelper::parameterToBool(const QString& parameter) {
    if (parameter.isEmpty()) return false;
    QString p = parameter.toLower();
    if (parameter == "1" || parameter == "x" || parameter == "y") return true;
    if (parameter == "0" || parameter == "n") return false;
    return parameter.startsWith("t") || parameter.startsWith("y");
}

//
// Append to new URL
//
const QString HttpHelper::appendToUrl(const QString& baseUrl, const QString &toBeAppended) {
    QString url = baseUrl;
    if (toBeAppended.isEmpty()) return url;
    if (baseUrl.isEmpty()) return toBeAppended;
    if ((!url.endsWith('/') && toBeAppended.startsWith('/')) || (url.endsWith('/') && !toBeAppended.startsWith('/')))
        url.append(toBeAppended);
    else if (url.endsWith('/') && toBeAppended.startsWith('/'))
        url.append(toBeAppended.midRef(1));
    else
        url.append("/" + toBeAppended);
    return url;
}

//
// Remove the query string of an url
// http://www.xy.com/path?a=1&b=2 => http://www.xy.com/path
//
const QString HttpHelper::removeQueryString(const QString& url) {
    if (!url.contains('?') && !url.contains('&')) return url;
    // normal I'd look only for ?, but looking for & as well fixex malformed URLs as well
    int i = url.indexOf('?');
    int j = url.indexOf('&');
    if (i<=j && i>=0) return url.left(i);
    if (j>=0) return url.left(j);
    // actually I should never get here
    return url;
}

//
// IP expand: 127.0.0.1 => 127.000.000.001
// IP collapse: 127.000.000.001 => 127.0.0.1
//
const QString HttpHelper::formatIPAddress(const QString& ip, bool expand) {
    // not valid, just return entry string
    QString fIp;
    if (ip.isEmpty() || ip.count('.') != 3) return ip;
    fIp = "";
    QStringList parts = ip.trimmed().split('.');
    if (parts.count() != 4) return ip; // invalid
    for (int i=0; i< parts.count(); i++) {
        QString fPart;
        if (expand)
            fPart = QString("00" + parts.at(i)).right(3);
        else {
            fPart = parts.at(i);
            fPart.replace(QRegExp("^0*0"), "");
            if (fPart.isEmpty()) fPart = "0";
        }
        if (i>0) fIp += ".";
        fIp += fPart;
    }
    return fIp;
}
